package com.crm.api.service.impl;

import com.crm.api.entity.Business;
import com.crm.api.mapper.BusinessMapper;
import com.crm.api.mapper.EmployeeMapper;
import com.crm.api.service.BusinessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务服务实现类
 */
@Slf4j
@Service
public class BusinessServiceImpl implements BusinessService {

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Map<String, Object> getBusinesses(Integer page, Integer size, String businessName, 
                                           String businessStatus, Integer customerId, 
                                           Integer businessTypeId, Integer responsibleEmployeeId) {
        
        // 计算偏移量
        Integer offset = (page - 1) * size;
        
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        params.put("offset", offset);
        params.put("pageSize", size);
        params.put("limit", size);  // 为了兼容性保留
        params.put("businessName", businessName);
        params.put("businessStatus", businessStatus);
        params.put("customerId", customerId);
        params.put("businessTypeId", businessTypeId);
        params.put("responsibleEmployeeId", responsibleEmployeeId);
        
        // 查询数据
        List<Map<String, Object>> businesses = businessMapper.findBusinessesWithDetails(params);
        Integer total = businessMapper.countBusinesses(params);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("data", businesses);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", (total + size - 1) / size);
        
        return result;
    }

    @Override
    public Business getBusinessById(Integer id) {
        return businessMapper.findById(id);
    }

    @Override
    public Map<String, Object> getBusinessDetailById(Integer id) {
        return businessMapper.findByIdWithDetails(id);
    }

    @Override
    public Business createBusiness(Business business, String creatorUsername) {
        // 获取创建人ID
        Integer createdBy = employeeMapper.findByUsername(creatorUsername).getId();
        business.setCreatedBy(createdBy);
        
        // 生成业务编号
        String businessCode = generateBusinessCode();
        business.setBusinessCode(businessCode);
        
        // 设置创建时间
        business.setCreatedAt(new Date());
        business.setUpdatedAt(new Date());
        
        // 插入数据
        businessMapper.insert(business);
        
        return business;
    }

    @Override
    public Business updateBusiness(Business business) {
        // 检查业务是否存在
        Business existingBusiness = businessMapper.findById(business.getId());
        if (existingBusiness == null) {
            return null;
        }
        
        // 设置更新时间
        business.setUpdatedAt(new Date());
        
        // 更新数据
        businessMapper.update(business);
        
        return businessMapper.findById(business.getId());
    }

    @Override
    public boolean deleteBusiness(Integer id) {
        // 检查业务是否存在
        Business business = businessMapper.findById(id);
        if (business == null) {
            return false;
        }
        
        // 删除业务
        businessMapper.deleteById(id);
        return true;
    }

    @Override
    public boolean updateBusinessStatus(Integer id, String businessStatus) {
        // 检查业务是否存在
        Business business = businessMapper.findById(id);
        if (business == null) {
            return false;
        }
        
        // 更新状态
        businessMapper.updateStatus(id, businessStatus, new Date());
        return true;
    }

    @Override
    public boolean updateBusinessProgress(Integer id, String progressNotes) {
        // 检查业务是否存在
        Business business = businessMapper.findById(id);
        if (business == null) {
            return false;
        }
        
        // 更新进度备注
        businessMapper.updateProgress(id, progressNotes, new Date());
        return true;
    }

    @Override
    public Map<String, Object> getBusinessStats(String startDate, String endDate, Integer businessTypeId) {
        Map<String, Object> params = new HashMap<>();
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("businessTypeId", businessTypeId);
        
        // 获取各种统计数据
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalCount", businessMapper.getTotalCount(params));
        stats.put("totalAmount", businessMapper.getTotalAmount(params));
        stats.put("statusStats", businessMapper.getStatusStats(params));
        stats.put("typeStats", businessMapper.getTypeStats(params));
        stats.put("monthlyStats", businessMapper.getMonthlyStats(params));
        
        return stats;
    }

    @Override
    public List<Map<String, Object>> getCustomerBusinessStats() {
        return businessMapper.getCustomerBusinessStats();
    }

    /**
     * 生成业务编号
     */
    private String generateBusinessCode() {
        // 获取当前最大编号
        String maxCode = businessMapper.getMaxBusinessCode();
        
        if (maxCode == null) {
            return "BUS001";
        }
        
        // 提取数字部分
        String numberPart = maxCode.substring(3);
        int number = Integer.parseInt(numberPart) + 1;
        
        // 格式化为3位数字
        return String.format("BUS%03d", number);
    }
}